package com.xyrl.project.manager.core;

import com.xyrl.common.base.exception.OtherLoginException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Api(value = "filter错误处理", description = "filter错误处理")
@Slf4j
public class ErrorController extends BasicErrorController {

    public ErrorController() {
        super(new DefaultErrorAttributes(true),
                new ErrorProperties());
    }

    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        log.info("错误状态:{}", body.get("status"));
        if (body.containsKey("exception")) {
            String exception = body.get("exception").toString();
            if (exception.equalsIgnoreCase(OtherLoginException.class.getName())) {
                throw new OtherLoginException("token 过期请重新登录");
            } else if (exception.equalsIgnoreCase(AuthorizationException.class.getName())) {
                throw new AuthorizationException();
            } else if (exception.equalsIgnoreCase(AuthenticationException.class.getName())) {
//                throw new AuthenticationException();
            }
        }
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    @Override
    public String getErrorPath() {
        return "error/error";
    }

}
